package com.black.web.controller.system;

import com.alibaba.excel.EasyExcel;
import com.black.common.core.domain.R;
import com.black.system.domain.req.system.query.SysRoleQueryReq;
import com.black.system.domain.resp.system.SysRoleResp;
import com.black.system.service.SysRoleService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author L
 */
@Api(tags = "后台-角色管理Api")
@RestController
@RequestMapping("/admin/role")
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;

    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @ApiOperation(value = "分页查询角色信息")
    @GetMapping("/list")
    public R<PageInfo<SysRoleResp>> list(SysRoleQueryReq req) {
        PageInfo<SysRoleResp> pageInfo = this.sysRoleService.paginationQuery(req);
        return R.ok(pageInfo);
    }

    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @ApiOperation(value = "根据id查询角色信息")
    @GetMapping("/{id}")
    public R<SysRoleResp> findById(@PathVariable(value = "id") Long id) {
        SysRoleResp sysRoleResp = this.sysRoleService.findById(id);
        return R.ok(sysRoleResp);
    }

    @PreAuthorize("@ss.hasPermi('system:role:export')")
    @ApiOperation(value = "导出到Excel")
    @PostMapping("/export")
    public void download(HttpServletResponse response, SysRoleQueryReq req, Long[] ids) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        // .xlsx 文件的  mine-type类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        // 内容响应编码
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("role", "UTF-8").replaceAll("\\+", "%20");
        // 告诉浏览器，文件名称叫什么
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 查询数据库，向EasyExcel写入数据
        List<SysRoleResp> data = this.sysRoleService.export(req, ids);
        EasyExcel.write(response.getOutputStream(), SysRoleResp.class).sheet().doWrite(data);
    }

}
